# -*- coding: utf-8 -*-
# filename: handle.py

import web
import json
import re
from configcenter import configCenter
class Sign(object):
    def POST(self):
        try:
            web.header("Access-Control-Allow-Origin", "*")
            web.header('content-type','text/json')
            webData = web.input()
            name = webData.name
            mobile = webData.mobile
            className = webData.className
            smsCode = webData.smsCode
            message = webData.message
            pattern1 = re.compile(r'1[0-9]{10}')
            pattern2 = re.compile(u"^[\u4E00-\u9FA5]+$")
            if not pattern1.match(mobile):
                result = {'result': False,'msg':'手机号错误'}
            elif not pattern2.match(name):
                result = {'result': False,'msg':'姓名错误，请输入您的真实姓名'}
            else:
                cc = configCenter()
                config = cc.getConfig()
                host = config.get("global", "ip")
                port = config.get("global", "port")
                user = config.get("global", "user")
                pw = config.get("global", "password")
                database = config.get("global", "database")
                db = web.database(dbn='mysql', host=host, port=int(port), user=user, pw=pw, db=database)
                myvar = dict(mobile=mobile)
                cr = db.select('checks', myvar, where="mobile = $mobile")
                if len(cr)> 0 and cr[0].smscode == smsCode:
                    sr = db.select('sign', myvar, where="mobile = $mobile")
                    if len(sr) == 0:
                        db.insert('sign', name=name, mobile=mobile, class_name=className,message=message)
                        result = {'result':True}
                        return json.dumps(result)
                    else:
                        result = {'result': False, 'msg': '该手机签到已完成，请勿重复签到'}
                else:
                    result = {'result': False,'msg':'验证码错误'}
            return json.dumps(result)
        except Exception as e:
            return e.args